/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Collir.java
 *
 * Created on 15/03/2011, 12:06:31
 */
package vistas;

import Renderers.LabelRenderer;
import comu.Utilitats;
import controlador.CollitaControlador;
import controlador.ProduccioControlador;
import controlador.UnitatsMesuraControlador;
import entity.Camp;
import entity.Collita;
import entity.Produccio;
import entity.UnitatsMesura;
import java.io.IOException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import vistas.dialogs.DialogImprimirTraz;
import vistas.dialogs.DialogSituarParcela;
import vistas.textImg.Textos;

/**
 *
 * @author David
 */
public final class Collir extends javax.swing.JFrame implements Observer {

    JFrame menu;
    UnitatsMesuraControlador unitatsMesura;
    ProduccioControlador produccions;
    CollitaControlador collites;
    DialogSituarParcela situarParcela;
    Produccio produccio;
    Collita collita;

    /** Creates new form Collir */
    Collir(JFrame menu, Collita collita , Produccio produccio) {
        this.menu = menu;
        this.collita = collita;
        this.produccio = produccio;
        
        unitatsMesura = new UnitatsMesuraControlador();
        produccions = new ProduccioControlador();
        collites = new CollitaControlador();
        
        initComponents();
        
        Utilitats.centrarVentana(this);
        try {
            if (this.collita != null) {
                update(null, this.collita);
//                ftfData.setText(Configuracio.sdf_ddMMyyyy.format(this.collita.getData()));
//                ftfTotal.setText(String.valueOf(this.collita.getQuantitat()));
//                if (situarParcela == null) {
//                    List<Produccio> veins = produccions.findProduccioEntitiesByCamp(this.collita.getProduccioId().getCampId(),false);
//                    veins.remove(this.collita.getProduccioId());
//                    situarParcela = new DialogSituarParcela(this, true, this.collita.getProduccioId().getCampId(),this.collita.getProduccioId(),veins,false);
//                }
            }else if(this.produccio != null){
                update(null, this.produccio);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        btAvui = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cbUnitat = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        btCancelar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        ftfTotal = new javax.swing.JFormattedTextField();
        ftfCadaCaixa = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        ftfCaixes = new javax.swing.JFormattedTextField();
        btAceptar = new javax.swing.JButton();
        btMenu = new javax.swing.JButton();
        lblMapaCamp = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        taDescripcio = new javax.swing.JTextArea();
        dcDataCollita = new com.toedter.calendar.JDateChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel3.setText(Textos.COLLIR_LABEL_DATA);

        btAvui.setText(Textos.COLLIR_BOTO_AVUI);
        btAvui.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAvuiActionPerformed(evt);
            }
        });

        jLabel2.setText(Textos.COLLIR_LABEL_UNITATMESURA);

        cbUnitat.setModel(Utilitats.getComboBoxModel(unitatsMesura.findUnitatsMesuraEntitiesForCollir()));
        cbUnitat.setAutoscrolls(true);
        cbUnitat.setRenderer(new LabelRenderer());
        cbUnitat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbUnitatActionPerformed(evt);
            }
        });

        jLabel1.setText(Textos.COLLIR_LABEL_QUANTITAT);

        btCancelar.setText(Textos.COMU_BOTO_CANCELAR);
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        jLabel5.setText(Textos.COLLIR_LABEL_PER_CADA);

        ftfTotal.setText("0");
        ftfTotal.setFont(Textos.FONT_GRAN);

        ftfCadaCaixa.setText("0");
        ftfCadaCaixa.setFont(Textos.FONT_GRAN);
        ftfCadaCaixa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                ftfCaixesKeyTyped(evt);
            }
        });

        jLabel4.setText(Textos.COLLIR_LABEL_CAIXES);

        ftfCaixes.setText("0");
        ftfCaixes.setFont(Textos.FONT_GRAN);
        ftfCaixes.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                ftfCaixesKeyTyped(evt);
            }
        });

        btAceptar.setText(Textos.COMU_BOTO_ACCEPTAR);
        btAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAceptarActionPerformed(evt);
            }
        });

        btMenu.setText(Textos.COMU_BOTO_MENU);
        btMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btMenuActionPerformed(evt);
            }
        });

        lblMapaCamp.setText(" ");
        lblMapaCamp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lblMapaCampMouseClicked(evt);
            }
        });

        taDescripcio.setColumns(14);
        taDescripcio.setEditable(false);
        taDescripcio.setRows(5);
        jScrollPane2.setViewportView(taDescripcio);

        dcDataCollita.setDate(GregorianCalendar.getInstance().getTime());

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel2)
                            .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 91, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                .add(dcDataCollita, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 162, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(btAvui, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 101, Short.MAX_VALUE))
                            .add(org.jdesktop.layout.GroupLayout.LEADING, cbUnitat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 176, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(23, 23, 23))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel1)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(ftfTotal, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 276, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(jLabel5)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(ftfCadaCaixa, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 276, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(jLabel4)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(ftfCaixes, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 276, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(layout.createSequentialGroup()
                                    .add(1, 1, 1)
                                    .add(lblMapaCamp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 147, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 212, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                    .add(btAceptar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 181, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                        .add(btCancelar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 183, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(btMenu)))))
                        .addContainerGap(24, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .addContainerGap()
                            .add(btAvui, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 38, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .addContainerGap(20, Short.MAX_VALUE)
                            .add(dcDataCollita, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE))))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(cbUnitat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(ftfCaixes, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(ftfCadaCaixa, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 38, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(ftfTotal, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(7, 7, 7)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btAceptar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 57, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(btCancelar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(lblMapaCamp, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 200, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btMenu, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAvuiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAvuiActionPerformed
        dcDataCollita.setDate(GregorianCalendar.getInstance().getTime());
}//GEN-LAST:event_btAvuiActionPerformed

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        ftfCadaCaixa.setText("0");
        ftfCaixes.setText("0");
        ftfTotal.setText("0");
        taDescripcio.setText("");
        dcDataCollita.setDate(GregorianCalendar.getInstance().getTime());
        if(collita!= null){
            collita = null;
            btMenuActionPerformed(evt);
        }else{
            collita = null;
        }
    }//GEN-LAST:event_btCancelarActionPerformed

    private void btAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAceptarActionPerformed

                    Date data = dcDataCollita.getDate();
                    Integer quantitat = Integer.valueOf(ftfTotal.getText());
                    if (quantitat != 0) {
                        UnitatsMesura unitat = (UnitatsMesura)cbUnitat.getSelectedItem();
                        if(unitat!= null){
                        try {
                            if (collita == null) {
                                collita = new Collita();
                                collita.setData(data);
                                collita.setQuantitat(quantitat);
                                collita.setProduccioId(produccio);
                                collita.setUnitatsMesuraId((UnitatsMesura) cbUnitat.getSelectedItem());
                                collites.create(collita);
                                new DialogImprimirTraz(this, true, collita).setVisible(true);
                                btCancelarActionPerformed(evt);
                                update(null, null);
                            } else {
                                collita.setData(data);
                                collita.setQuantitat(quantitat);
                                collita.setProduccioId(produccio);
                                collita.setUnitatsMesuraId((UnitatsMesura) cbUnitat.getSelectedItem());
                                collites.edit(collita);
                                new DialogImprimirTraz(this, true, collita).setVisible(true);
                                btCancelarActionPerformed(evt);
                                btMenuActionPerformed(evt);
                            }
                        } catch (Exception e) {
                            JOptionPane.showMessageDialog(this, Textos.COMU_ERROR_BASE_DADES, "", JOptionPane.ERROR_MESSAGE);
                        }
                        }else{
                            JOptionPane.showMessageDialog(this,Textos.COLLIR_INFO_UNITAT,"",JOptionPane.WARNING_MESSAGE);
                        }
                    }else{
                        JOptionPane.showMessageDialog(this,Textos.COLLIR_INFO_QUANTITAT,"",JOptionPane.WARNING_MESSAGE);
                    }
}//GEN-LAST:event_btAceptarActionPerformed

    private void cbUnitatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbUnitatActionPerformed
        UnitatsMesura unitatMesura = (UnitatsMesura) cbUnitat.getSelectedItem();
        if(unitatMesura != null){
            jLabel4.setText(unitatMesura.getUnitatsMesuraId().getNom());
        }
    }//GEN-LAST:event_cbUnitatActionPerformed

    private void btMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMenuActionPerformed
        if (menu != null) {
           if(General.class.isInstance(menu)){
                ((General)menu).update(null, null);
            }
            menu.setVisible(true);
            this.setVisible(false);
        }
    }//GEN-LAST:event_btMenuActionPerformed

    private void ftfCaixesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ftfCaixesKeyTyped
        if ((!ftfCaixes.getText().equals("0")) && (!ftfCadaCaixa.getText().equals("0"))) {
            try {
                ftfTotal.setText(String.valueOf(Integer.parseInt(ftfCadaCaixa.getText()) * Integer.parseInt(ftfCaixes.getText())));
            } catch (Exception e) {
                ftfTotal.setText("0");
            }
        }
}//GEN-LAST:event_ftfCaixesKeyTyped

    private void lblMapaCampMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblMapaCampMouseClicked
        Camp camp = produccio.getCampId();
        List<Produccio> veins = produccions.findProduccioEntitiesByCamp(camp, false);
        veins.remove(produccio);
        new DialogSituarParcela(this, true, camp, produccio, veins, false).setVisible(true);
    }//GEN-LAST:event_lblMapaCampMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAceptar;
    private javax.swing.JButton btAvui;
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btMenu;
    private javax.swing.JComboBox cbUnitat;
    private com.toedter.calendar.JDateChooser dcDataCollita;
    private javax.swing.JFormattedTextField ftfCadaCaixa;
    private javax.swing.JFormattedTextField ftfCaixes;
    private javax.swing.JFormattedTextField ftfTotal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblMapaCamp;
    private javax.swing.JTextArea taDescripcio;
    // End of variables declaration//GEN-END:variables

    public void update(Observable o, Object o1) {
        if(Produccio.class.isInstance(o1)){
            try {
                collita = null;
                btCancelarActionPerformed(null);
                produccio = (Produccio) o1;
                Utilitats.adabtarImatgeAlLabel(lblMapaCamp, produccio.getCampId().getImg());
                taDescripcio.setText(Utilitats.getDescripcio(produccio));
            } catch (IOException ex) {
                Logger.getLogger(Collir.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else if(Collita.class.isInstance(o1)){
            try {
                collita = (Collita) o1;
                produccio = collita.getProduccioId();
                Utilitats.adabtarImatgeAlLabel(lblMapaCamp, produccio.getCampId().getImg());
                dcDataCollita.setDate(collita.getData());
                cbUnitat.setSelectedItem(collita.getUnitatsMesuraId());
                ftfTotal.setText(String.valueOf(collita.getQuantitat()));
                taDescripcio.setText(Utilitats.getDescripcio(produccio));
            } catch (IOException ex) {
                Logger.getLogger(Collir.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }else{
            cbUnitatActionPerformed(null);
            if(produccio!= null){
                try {
                    Utilitats.adabtarImatgeAlLabel(lblMapaCamp, produccio.getCampId().getImg());
                } catch (IOException ex) {
                    Logger.getLogger(Collir.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        }
    }

    private DefaultListModel getListModel(List llista) {
        DefaultListModel modelP = new DefaultListModel();
        for (int i = 0; i < llista.size(); i++) {
            modelP.addElement(llista.get(i));
        }
        return modelP;
    }
}
